<template>
  <div class="parameter-product">
    <div class="flex justify-center mb-6">
      <span class="text-xl font-bold text-gray-800">采购入库</span>
    </div>
    <!-- 条件查询区域 -->
    <div class="search-container mb-4">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="采购订单号">
              <el-input v-model="searchForm.purchaseCode" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="到货单号">
              <el-input v-model="searchForm.arrivalCode" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购入库单号">
              <el-input v-model="searchForm.taskCode" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="添加类型">
              <el-select v-model="searchForm.addType" placeholder="全部" clearable style="width: 100px;">
                <el-option label="全部" value="0" />
                <el-option label="快捷流程" value="2" />
                <el-option label="标准流程" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库状态">
              <el-select v-model="searchForm.stockStatus" placeholder="全部" style="width: 100px;" clearable>
                <el-option label="全部" value="0" />
                <el-option label="未入库" value="1" />
                <el-option label="部分入库" value="2" />
                <el-option label="全部入库" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商">
              <el-input v-model="searchForm.supplier" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开始日期">
              <el-date-picker
                v-model="searchForm.startTime"
                type="date"
                placeholder="开始日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束日期">
              <el-date-picker
                v-model="searchForm.endTime"
                type="date"
                placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" class="form-actions">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button type="primary" @click="handlePrint" :disabled="selectedRows.length === 0">打印</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-table :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" />
      <el-table-column type="index" prop="serial" label="序号"/>
      <el-table-column prop="arrivalCode" label="到货单号" />
      <el-table-column prop="purchaseCode" label="采购订单号" />
      <el-table-column label="添加类型">
        <template #default="scope">
          <span v-if="scope.row.addType === 1">标准流程</span>
          <span v-else-if="scope.row.addType === 2">快捷流程</span>
          <span v-else>{{ scope.row.addType }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="supplier" label="供应商" />
      <el-table-column prop="purchaseDate" label="采购日期" />
      <el-table-column prop="purchaseUser" label="采购人员" />
      <el-table-column prop="content" label="入库内容" />
      <el-table-column prop="arrivalDate" label="到货日期" />
      <el-table-column label="入库状态">
        <template #default="scope">
          <span v-if="scope.row.stockStatus === 1">未入库</span>
          <span v-else-if="scope.row.stockStatus === 2">部分入库</span>
          <span v-else-if="scope.row.stockStatus === 3">全部入库</span>
          <span v-else>{{ scope.row.stockStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <span class="clickable text-warning" @click="handleTaskDetail(scope.row)" style="margin-right: 20px;">任务详情</span>
          <span v-if="scope.row.stockStatus !==3 " class="clickable text-warning" @click="handleInbound(scope.row)">入库</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 可扩展弹窗等功能 -->
    <!-- <StockSettingDialog v-model="dialogVisible" :current-row="currentRow" @on-save="handleSaveSuccess" /> -->
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { query } from '@/api/stockIn/purchaseStockIn.js'
import { useRouter } from 'vue-router'

// 选中的行数据
const selectedRows = ref([])
//声明打印参数
const printParams = ref([])

// 分页相关参数
const page = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)
const tableData = ref([])
//声明路由
const router = useRouter()
// 查询表单参数
const searchForm = ref({
  purchaseCode: '',
  arrivalCode: '',
  taskCode: '',
  addType: '',
  stockStatus: '',
  supplier: '',
  startTime: '',
  endTime: ''
})

// 加载状态
const loading = ref(false)

async function init() {
  try { 
    // 显示加载状态
    loading.value = true
    // 使用对象扩展运算符简化参数构建
    let params = {
      a_type: 'purchase',
      page: page.value,
      pageSize: pageSize.value,
      purchaseStockIn:{...searchForm.value }
      
    }
    const res = await query(params)
    console.log(params)
    if (res.code === 200) {
      tableData.value = res.data.list
      totalCount.value = res.data.total
    } else {
      console.error('获取数据失败:', res)
      // 可以在这里添加错误提示
      // ElMessage.error(`获取数据失败: ${res.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error('接口请求错误:', error)
    // ElMessage.error('网络错误，请稍后重试')
  } finally {
    // 无论成功失败都关闭加载状态
    loading.value = false
  }
}

onMounted(() => {
  init()
})

const handleQuery = () => {
  page.value = 1
  init()
}
// 处理打印功能
const handlePrint = () =>{
  // 打印逻辑，可结合 print-js 或 window.print()
  router.push({
    name: 'purchasePrint',
    query: {
      printType: 'batch',
      printData: JSON.stringify(printParams.value)  
    }
   })
}

// 处理多选框选择变化
function handleSelectionChange(rows) {
  selectedRows.value = rows
  console.log('当前选择的行:', selectedRows.value)  

  printParams.value = rows.map(row => ({
    purchaseCode: row.purchaseCode,
    supplier: row.supplier,
    taskCode: row.taskCode,
    purchaseDate: row.purchaseDate,
    purchaseUser: row.purchaseUser,
    taskId: row.id
}));
}

const handleSizeChange = newSize => {
  pageSize.value = newSize
  page.value = 1
  init()
}
const handleCurrentChange = newPage => {
  page.value = newPage
  init()
}

const handleTaskDetail = row => {
  console.log('查看任务详情：', row)
  // 可跳转详情页或弹窗
}
const handleInbound = row => {
  console.log('执行入库操作：', row)
  // 调用入库接口，更新数据状态
  router.push({
    name: 'purchaseStockIn',
    query: {
      arrivalCode: row.arrivalCode,
      purchaseCode: row.purchaseCode,
      supplier: row.supplier,
      arrivalDate: row.arrivalDate,
      taskCode: row.taskCode,
      taskId: row.id,
    }
  })
}
</script>

<style scoped>
.clickable {
  cursor: pointer;
  color: #409eff;
}
.demo-pagination-block {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
  margin: 20px 0;
}
.search-container {
  margin: 5px;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}
.search-form {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.form-actions {
  display: flex;
  align-items: center;
}
</style>